import redis
from django.shortcuts import render

# Create your views here.
import json
from rest_framework.views import APIView
from django.http import HttpResponse
from . import tasks
from django.utils.encoding import escape_uri_path

from celery.result import AsyncResult
from datetime import datetime, timedelta
# from django.contrib.gis.geoip2 import GeoIP2
from  .models import  Celery_result
from django.core import serializers
from .myredis import My_redis

def time_handler(target_time: str):
    '''
    utc世界时间转 北京时间
    :param target_time:
    :return:
    '''
    _data = datetime.strptime(target_time, '%Y-%m-%dT%H:%M:%S.%fZ')
    local_time = _data + timedelta(hours=8)
    end_time = local_time.strftime("%Y-%m-%d %H:%M:%S")
    return end_time


# 执行断网任务的执行 ，返回执行结果，和状态
# class Disconnected(APIView):
#     def get(self, request):
#         print('get request')
#         res = tasks.disconnected_network.apply_async()
#         # 用get拿到返回的结果
#         print(f'任务结果：disconnected_network ID ：{res.id}   result :{res.status}')
#         data = {
#             "msg": "OK",
#             "taskid": res.id,
#             "status": res.status
#         }
#
#         return HttpResponse(json.dumps(data))


class QueryTask(APIView):
    def get(self, request):
        try:
            ts = Celery_result.objects.all().order_by('-id')[:20]
            # 实例化序列   django里面有个serializers方法可以，直接把查询的结果转成json数据
            ret_ts = serializers.serialize('json', ts)
            data = {
                "msg": json.loads(ret_ts),
                "errorcode": 0
            }
            return HttpResponse(json.dumps(data))

        except Exception as e:
            print(e)
            data = {
                "msg": [],
                "errorcode": 0
            }
            return HttpResponse(json.dumps(data))



# 查询任务的状态
class Quereyredis(APIView):

    def post(self,request):
        print('Quereyredis')
        value = request.data
        print("前端传来的",value)

        val= My_redis().get_value("celery-task-meta-"+value)
        if val:
            print("查询redis的结果:",val.decode('utf-8'))
            res_val = val.decode('utf-8')
            print("查询redis的结果:",type(res_val))
            json_val = json.loads(res_val)
            data = {
                "status":json_val['status'],
                "task_id": json_val['task_id'],
                "result":json_val['result'],
                'errorCode':200
            }

            # 更新 celery——result 表的状态 和下载地址
            try:
                ts = Celery_result.objects.get(taskid=value)
                print(ts.id)

                ts.status = json_val['status']
                ts.res_url = json_val['result']
                ts.save()


            except Celery_result.DoesNotExist:
                print(" taskid  DoesNotExist")

            return HttpResponse(json.dumps(data))
        else:
            data={
                'errorCode': -1,
                'msg':"No has has redis result! try again later!"
            }
            return HttpResponse(json.dumps(data))




# 处理
class Pretreatment(APIView):
    def post(self, request):
        formin = request.body
        dt = json.loads(formin)
        print("接收到请求,Pretreatment  开始进行分类处理 ")
        choosecheck = dt['choose']
        print(f"选择:{choosecheck}")
        #       判断要处理的内容
        if choosecheck == '1':  # 全网断网数据
            res = tasks.disconnected_network.apply_async()
            # 用get拿到返回的结果
            print(f'任务结果：disconnected_network ID ：{res.id}   result :{res.status}')
            ts = Celery_result(taskid=res.id, status=res.status,create_timestamp=datetime.now())
            ts.save()

            data = {
                "msg": "请求成功,准备执行查询",
                "taskid": res.id,
                "status": res.status
            }
            return HttpResponse(json.dumps(data))

        elif choosecheck == '2':  # 合作方，所有时间段内的收益
            partner = dt.get('partnerid', None)
            starttime = dt.get('startdate', None)
            endtime = dt.get('enddate', None)

            if partner and starttime and endtime:
                dp = {"partnerid": (dt["partnerid"]), "starttime": time_handler(dt["startdate"]),
                      "endtime": time_handler(dt["enddate"])}
                # 要把传进来的数据进行解析，作为tasks的任务参数
                res = tasks.partner_revenue.apply_async(kwargs=dp)

                print(f'任务结果：disconnected_network ID ：{res.id}   result :{res.status}')
                ts = Celery_result(taskid=res.id, status=res.status,create_timestamp=dt["startdate"])
                ts.save()

                data = {
                    "msg": "请求成功,准备执行查询",
                    "taskid": res.id,
                    "status": res.status
                }
                return HttpResponse(json.dumps(data))
            else:
                data = {
                    "msg": "请输入对应的参数,合作方id ，开始和结束日期 ",
                }
                return HttpResponse(json.dumps(data))

        elif choosecheck == '3':  # 站点 ，时间段  收益
            starttime = dt.get('startdate', None)
            endtime = dt.get('enddate', None)
            station = dt.get("station", None)
            print(station,starttime,endtime)
            if station and starttime and endtime:
                dp = {"partnerid": '',"station": dt["station"], "starttime": time_handler(dt["startdate"]),
                      "endtime": time_handler(dt["enddate"])}
                res = tasks.general_queries.apply_async(kwargs=dp)

                ts = Celery_result(taskid=res.id, status=res.status,create_timestamp=dt["startdate"])
                ts.save()

                data = {
                    "msg": "请求成功,准备执行查询",
                    "taskid": res.id,
                    "status": res.status
                }

                return HttpResponse(json.dumps(data))
            else:
                data = {
                    "msg": "请输入对应的参数,站点id ，开始和结束日期 ",
                }
                return HttpResponse(json.dumps(data))

        elif choosecheck == '4':  # 站点 ，时间段  收益
            starttime = dt.get('startdate', None)
            endtime = dt.get('enddate', None)
            station = dt.get("station", None)
            if station and starttime and endtime:
                dp = {"partnerid": '', "station": dt["station"], "starttime": time_handler(dt["startdate"]),
                      "endtime": time_handler(dt["enddate"])}
                res = tasks.general_queries.apply_async(kwargs=dp)

                ts = Celery_result(taskid=res.id, status=res.status,create_timestamp=dt["startdate"])
                ts.save()

                data = {
                    "msg": "请求成功,准备执行查询",
                    "taskid": res.id,
                    "status": res.status
                }

                return HttpResponse(json.dumps(data))
            else:
                data = {
                    "msg": "请输入对应的参数,站点id ，开始和结束日期 ",
                }
                return HttpResponse(json.dumps(data))

        elif choosecheck == '5':  # 站点 ，时间段  收益
            starttime = dt.get('startdate', None)
            endtime = dt.get('enddate', None)
            station = dt.get("station", None)
            if station and starttime and endtime:
                dp = {"partnerid": '', "station": dt["station"], "starttime": time_handler(dt["startdate"]),
                      "endtime": time_handler(dt["enddate"])}
                res = tasks.general_queries.apply_async(kwargs=dp)
                ts = Celery_result(taskid=res.id, status=res.status,create_timestamp=dt["startdate"])
                ts.save()
                data = {
                    "msg": "请求成功,准备执行查询",
                    "taskid": res.id,
                    "status": res.status
                }

                return HttpResponse(json.dumps(data))
            else:
                data = {
                    "msg": "请输入对应的参数,站点id ，开始和结束日期 ",
                }
                return HttpResponse(json.dumps(data))


# class Partner_revenue(APIView):
#     def post(self, request):
#         form = request.body  # 从前端接收的
#         print("接收到Partner_revenue 的请求了")
#         dt = json.loads(form)
#         dp = {"partnerid": (dt["partnerid"]), "starttime": time_handler(dt["startdate"]),
#               "endtime": time_handler(dt["enddate"])}
#         print(dp)
#
#         # 要把传进来的数据进行解析，作为tasks的任务参数
#         res = tasks.partner_revenue.apply_async(kwargs=dp)
#         print(f'任务结果：disconnected_network ID ：{res.id}   result :{res.status}')
#         data = {
#             "msg": "OK",
#             "taskid": res.id,
#             "status": res.status
#         }
#
#         return HttpResponse(json.dumps(data))


# 查询taskid 任务的执行状态
class Querytaskid(APIView):
    '''
    查询任务id执行任务状态 ，
    params： taskid
    '''

    def post(self, request):
        taskid = request.data
        #   redis中taskid 对应的状态，接收传入进来的参数 ，获取结果
        task_result = AsyncResult(taskid)
        print(task_result.status)

        data = {
            "taskid": taskid,
            "status": task_result.status
        }
        return HttpResponse(json.dumps(data))


class Downfile(APIView):
    def post(self, request):
        print("post  downfile  ")
        downloadname = request.data
        print(type(downloadname))
        print(downloadname.split('/')[-1])
        with open(downloadname, 'rb') as f:
            # 将文件以二进制形式读取
            file_data = f.read()
        response = HttpResponse(file_data, content_type='application/octet-stream')
        # 设置响应头，告诉浏览器返回的是附件，并指定文件名
        response['Content-Disposition'] = 'attachment; filename={0}'.format(escape_uri_path(downloadname.split('/')[-1]))
        return response
